package com.ricohgag.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ricohgag.entity.RechargeLog;
import com.ricohgag.entity.VipUser;
import com.ricohgag.entity.custom.RechargeLogVo;
import com.ricohgag.mapper.RechargeLogMapper;
import com.ricohgag.service.RechargeLogService;
import com.ricohgag.service.VipUserService;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 肖晖
 * @since 2018-08-25
 */
@Service
public class RechargeLogServiceImpl extends ServiceImpl<RechargeLogMapper, RechargeLog> implements RechargeLogService {
    @Autowired
    private RechargeLogMapper rechargeLogMapper;
    @Autowired
    private VipUserService vipUserService;

    @Override
    public List<RechargeLog> selectRechargeLogs(Integer userId) throws Exception{

        List<RechargeLog> rechargeLogs = rechargeLogMapper.selectList(new QueryWrapper<RechargeLog>().eq("user_id", userId));
        return rechargeLogs;
    }

    @Override
    public List<RechargeLogVo> selectRechargeLogPage(String name, Page<RechargeLog> page, String startDate, String endDate) throws Exception{
        QueryWrapper<RechargeLog> qw = new QueryWrapper<>();

        if(name != null){
            VipUser vipUser = vipUserService.selectByName(name);
            if(vipUser != null){
                qw.eq("user_id", vipUser.getId());
            }

        }

        if(startDate!=null&&!"".equals(startDate) && endDate!=null&&!"".equals(endDate)){
            System.out.println("temmp");
            qw.between("add_time", startDate, endDate);
        }

        IPage<RechargeLog> rechargeLogIPage = rechargeLogMapper.selectPage(page, qw);
        List<RechargeLog> rechargeLogList = rechargeLogIPage.getRecords();
        List<RechargeLogVo> rechargeLogVos = new ArrayList<>();

        //循环分页中的数据依次放入包装类中
        for(RechargeLog rechargeLog:rechargeLogList){
            RechargeLogVo rechargeLogVo = new RechargeLogVo();
            //通过id查询用户对象，放入包装类中
            int userId = rechargeLog.getUserId();
            System.err.println("user: "+userId);
            VipUser vipUser = vipUserService.selectVipUserOne(userId);
            System.out.println("vipUser: "+vipUser);
            rechargeLogVo.setRechargeLog(rechargeLog);
            rechargeLogVo.setVipUser(vipUser);
            rechargeLogVos.add(rechargeLogVo);
        }

        Assert.assertSame(page, rechargeLogIPage);

        return rechargeLogVos;
    }

    @Override
    public int insertRechargeLogs(RechargeLog rechargeLog) throws Exception{

        return rechargeLogMapper.insert(rechargeLog);
    }
}
